package com.smart.manager.pop.repository;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Opt;
import com.smart.common.entities.core.Page;
import com.smart.common.entities.option.SelectOption;
import com.smart.manager.pop.entities.body.RDisLevel;
import com.smart.manager.pop.entities.models.PopDisLevel;
import com.smart.manager.pop.entities.models.query.QPopDisLevel;
import io.ebean.DB;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 支付中心-订单管理
 *
 * @author Administrator
 */

@Log4j2
@Service
@RequiredArgsConstructor
public class DisLevelRepository {


    public Page<PopDisLevel> pageList(RDisLevel.SearchBody search) {

        QPopDisLevel query = new QPopDisLevel();
        Opt.ofBlankAble(search.getName()).ifPresent(x->query.name.contains(x)) ;
        Opt.ofBlankAble(search.getNickName()).ifPresent(x->query.nickName.contains(x)) ;
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows()).order().code.asc();
        return new Page<PopDisLevel>().load(query.findPagedList());
    }

    /**
     * 添加
     *
     * @param form 形式
     */
    public void add(RDisLevel.EditBody form) {
        PopDisLevel one = new QPopDisLevel().code.eq(form.getCode()).setMaxRows(1).findOne();
        Assert.isNull(one ,"等级规则建失败:规则序号已存在");
        PopDisLevel record = BeanUtil.copyProperties(form, PopDisLevel.class);

        record.save();
    }

    /**
     * 更新
     *
     * @param id   id
     * @param form 形式
     */
    public void update(Long id, RDisLevel.EditBody form) {
        PopDisLevel record = new QPopDisLevel().id.eq(id).findOne();
        Assert.notNull(record, "等级规则数据不存在");
        BeanUtil.copyProperties(form, record);
        record.update();


    }

    /**
     * 批量删除
     *
     * @param idList id列表
     * @return int
     */
    public int delByIds(List<Long> idList) {
//        long count = new QPopDisLevel().id.in(idList).findStream().filter(PopDisLevel::locked).count();
//        Assert.isTrue(count == 0, "操作失败:存在已有数据的客户经理账号");
        return DB.deleteAll(PopDisLevel.class, idList);
    }

    /**
     * 获取一个等级
     * @param id
     * @return {@link PopDisLevel}
     */
    public PopDisLevel getOne(Long id){
        Optional<PopDisLevel> level = new QPopDisLevel().id.eq(id).setMaxRows(1).findOneOrEmpty();
        Assert.isFalse(level.isEmpty(),"未找到等级!");
        return level.get();
    }

    /**
     * 获取数据字典下拉选项
     * @return {@code List<SelectOption>}
     */
    public List<SelectOption> getOptions() {
        QPopDisLevel place = new QPopDisLevel();
        return place.findStream()
                .map(x -> new SelectOption().setLabel(x.getNickName()).setValue(x.getId().toString()).setDisabled(false))
                .collect(Collectors.toList());
    }



}
